package com.lei.emos.wx.config.xss;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * 参数字符串的转义
     * @param name
     * @return
     */
    @Override
    public String getParameter(String name) {
        //从父类中获取到value
        String value = super.getParameter(name);
        //判断value 不能为空和空值
        if (!StrUtil.hasEmpty(value)){
            //将value中的字符串转义
            value = HtmlUtil.filter(value);
        }
        return value;
    }

    /**
     * 参数字符串数组的转义
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        //从父类中获取字符串数组到values
        String[] values = super.getParameterValues(name);
        if (values!=null){
            for (int i=0;i<values.length;i++){
                String value = values[i];
                if (!StrUtil.hasEmpty(value)){
                    //将value中的字符串转义
                    value = HtmlUtil.filter(value);
                }
                values[i] =value;
            }
        }
        return values;
    }

    /**
     * 参数map的转义
     * @return
     */
    @Override
    public Map<String, String[]> getParameterMap() {
        //从父类中获取map到parameters
        Map<String,String[]> parameters = super.getParameterMap();
        LinkedHashMap<String,String[]> map = new LinkedHashMap<>();
        if (parameters!=null){
            for (String key:parameters.keySet()){
                String[] values = parameters.get(key);
                for (int i=0;i<values.length;i++){
                    String value = values[i];
                    if (!StrUtil.hasEmpty(value)){
                        //将value中的字符串转义
                        value = HtmlUtil.filter(value);
                    }
                    values[i] =value;
                }
                map.put(key,values);
            }
        }
        return map;
    }

    /**
     * 请求头的转义
     * @param name
     * @return
     */
    @Override
    public String getHeader(String name) {
        //从父类中获取请求头数据
        String value = super.getHeader(name);
        //判断value 不能为空和空值
        if (!StrUtil.hasEmpty(value)){
            //将value中的字符串转义
            value = HtmlUtil.filter(value);
        }
        return value;
    }

    /**
     * io流的转义
     * @return
     * @throws IOException
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        //获取读数据的io流
        InputStream in = super.getInputStream();
        //创建字符流 传入InputStream流 以及设置字符集
        InputStreamReader reader = new InputStreamReader(in, Charset.forName("UTF-8"));
        //性能提升使用 BufferedReader 缓冲流
        BufferedReader buffer = new BufferedReader(reader);
        StringBuffer body = new StringBuffer();
        //将数据读出
        String line = buffer.readLine();
        while (line!=null){
            body.append(line);
            line = buffer.readLine();
        }
        //关闭流
        buffer.close();
        reader.close();
        in.close();

        //读取出的json数据转换map对象
        Map<String,Object> map = JSONUtil.parseObj(body.toString());
        //对map对象转义
        Map<String,Object> result = new LinkedHashMap<>();
        //遍历出value
        for (String key : map.keySet()){
            Object val = map.get(key);
            //判断val是不是String类型
            if (val instanceof String){
                //val是否为空
                if (!StrUtil.hasEmpty(val.toString())){
                    //转义后添加进新的map
                    result.put(key,HtmlUtil.filter(val.toString()));
                }
            }
            //如果不是String类型 直接让val加入新的map
            else {
                result.put(key,val);
            }
        }
        //将result转成json对象 在转成io流
        String json = JSONUtil.toJsonStr(result);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(json.getBytes());
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }
}
